var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pictrue_from: [],
    pictrue_to:[],
    delivery_rate:0,
    driver_rate:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    that.setData({
      id:e.id
    });
    if (e.show) {
      that.setData({
        show: e.show
      })
    }
    that.setData({
      server: app.server
    })
    that.loadData();
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  rateChange(e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.index;
    this.setData(item_value);
  },
  bindGetUserInfo: function () {
    wx.redirectTo({
      url: '/pages/driver/order_receiver?id='+this.data.id,
    })
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    });
    util.getData("/atapi/delivery/process/orderDelivery", {
      'id': that.data.id
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.hideLoading();
        var odData = res.data.data;
        var pictrue_from = String(odData.pictrue_from).split(",");
        var pictrue_to = odData.pictrue_to?String(odData.pictrue_to).split(","):[];
        that.setData({
          id: odData.ID,
          name: odData.name,
          address: odData.address,
          goodsinfo: odData.goodsinfo || odData.loading_rule || odData.w_loading_rule,
          goodsinfo_from: odData.goodsinfo_from,
          goodsinfo_to: odData.goodsinfo_to,
          packages: odData.packages,
          package_from: odData.package_from,
          package_to: odData.package_to,
          remark_from: odData.remark_from,
          remark_to: odData.remark_to,
          box_number_out: odData.box_number_out,
          box_number_in: odData.box_number_in,
          delivery_rate: odData.delivery_rate,
          driver_rate: odData.driver_rate,
          pictrue_from: pictrue_from,
          pictrue_to:pictrue_to,
          goods_return: odData.goods_return,
          odData: odData,
          actionForm: 'put'
        })
        console.log(odData.is_delivery == 1 && !that.data.show)
        if (odData.is_delivery == 1 && !that.data.show){
          that.setData({
            modalName : 'hasDelivery'
          })
        }else{
          wx.getSetting({
            success(res) {
              console.log(res.authSetting)
              if (res.authSetting["scope.userInfo"] == true) {
                wx.showLoading({
                  title: '核查权限中...',
                  mask: true
                });
                //调用登录接口
                wx.login({
                  success: function (res1) {
                    console.log(res1)
                    if (res1.code) {
                      util.postData('/wechat/passport/tmslogin', {
                        code: res1.code
                      }, function (res, error) {
                        console.log(res); console.log(error)
                        wx.hideLoading();
                        app.globalData.session_key = res.data.session_key;
                        app.globalData.openid = res.data.openid;
                        app.globalData.unionid = res.data.unionid;
                        // if (res.data.success) {
                        //   var userData = res.data.data[0];
                        //   app.globalData.user_id = userData.ID;
                        //   app.globalData.truename = userData.name;
                        // } else {
                        //   wx.navigateTo({
                        //     url: '/pages/auth/phoneauth?receiver=' + that.data.id
                        //   })
                        // }
                      });
                    }
                  }
                });
              } else {
                that.setData({
                  modalName: 'bottomModal'
                })
              }
            }
          })
        }
        that.goodsDW();
      }
    });
  },
  formSubmit: function () {
    var that = this;
    if (that.data.delivery_rate == 0){
      wx.showToast({
        title: "请给货配评分",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (that.data.driver_rate == 0) {
      wx.showToast({
        title: "请给司机评分",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...'
    });
    util.postData("/atapi/delivery/process/deliveryFromReceiver", {
      'id': that.data.id,
      'delivery': that.data.odData.delivery,
      'shop': that.data.odData.shop,
      'package_to': that.data.package_to,
      'goodsinfo_to': that.data.goodsinfo_to,
      'pictrue_to': that.data.pictrue_to.join(","),
      'remark_to': that.data.remark_to || '',
      'box_number_in': that.data.box_number_in || 0,
      'delivery_user': app.globalData.user_id,
      'delivery_time_to': moment().format('YYYY-MM-DD '),
      'delivery_rate': that.data.delivery_rate,
      'driver_rate': that.data.driver_rate,
      'goods_return': that.data.goods_return||'',
      'is_delivery': 1,
      'name': that.data.name,
      'logs': '收货人员（' + app.globalData.truename + '）提交【' + that.data.name + '】的交接信息。货物数量：' + that.data.package + '，交付箱框：' + (that.data.box_number_in || 0) + '，货配评分：' + that.data.delivery_rate + '分，司机评分：' + that.data.driver_rate + '分。备注：' + (that.data.remark_to || '无')
    }, function (res, error) {
      wx.hideLoading();
      console.log(res); console.log(error)
      if (res.data.success) {
        that.setData({
          id: res.data.id
        })
        wx.showToast({
          title: "提交成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.setData({
                modalName: 'hasDelivery'
              })
            }, 3000)
          }
        });
      } else {
        wx.showToast({
          title: "提交失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  bindGoodsInfoInput: function (e) {
    var that = this;
    var goods = that.data.goods;
    var packages = 0, goodsinfo = [];

    var value = e.detail.value;
    var id = e.currentTarget.id;

    for (var i = 0; i < goods.length; i++) {
      if (goods[i].id == id) {
        goods[i].number_to = value;
      }
      goodsinfo.push(goods[i].name + '|' + goods[i].ratio + '|' + goods[i].number_to)
      packages += (Number(goods[i].number_to) || 0) * (Number(goods[i].ratio) || 0);
    }

    that.setData({
      goods: goods,
      package_to: packages,
      goodsinfo_to: goodsinfo.join(",")
    });

    return value;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
  },
  goodsDW: function () {
    var that = this;
    var goods = [];
    var goodsinfo_from = that.data.goodsinfo_from || that.data.goodsinfo;
    var goodsinfo_to = that.data.goodsinfo_to;
    var goodsinfo = that.data.goodsinfo;
    var _goodsinfo = String(goodsinfo).split(",");
    var _goodsinfo_from = String(goodsinfo_from).split(",");
    var _goodsinfo_to = String(goodsinfo_to).split(",");
    if (goodsinfo) {
      if (goodsinfo_to) {
        for (var i = 0; i < _goodsinfo.length; i++) {
          var _item = String(_goodsinfo[i]).split("|");
          var _item_from = String(_goodsinfo_from[i]).split("|");
          var _item_to = String(_goodsinfo_to[i]).split("|");
          console.log(_item_from)
          goods.push({ "id": "LDR" + i, "name": _item[0], "ratio": _item[1], "number": _item[2], "number_from": _item_from[2], "number_to": _item_to[2] });
        }
      } else {
        for (var i = 0; i < _goodsinfo_from.length; i++) {
          var _item = String(_goodsinfo[i]).split("|");
          var _item_from = String(_goodsinfo_from[i]).split("|");
          console.log(_item_from)
          goods.push({ "id": "LDR" + i, "name": _item[0], "ratio": _item[1], "number": _item[2], "number_from": _item_from[2], "number_to": 0 });
        }
      }
    }
    that.setData({
      goods: goods
    })
  },
  chooseDeliveryImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var pictruelist = that.data.pictrue_from;
    if (type == 'pictrueto'){
      pictruelist = that.data.pictrue_to;
    }
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server + '/atapi/delivery/process/uploadDeliveryScene',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          success: function (res) {
            var data = JSON.parse(res.data); console.log(data)
            if (data.success) {
              pictruelist.push(data.data);
              pictruelist = util.arrayDeleteEmpty(pictruelist);
              if (type == 'pictrueto') {
                that.setData({
                  pictrue_to: pictruelist
                });
              } else {
                that.setData({
                  pictrue_from: pictruelist
                });
              }
            } else {
              wx.showToast({
                title: "上传失败",
                image: '/images/wrong.png',
                duration: 2000
              });
            }
          },
          complete: function () {
            wx.hideLoading();
          }
        })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.pictrue_from;
    if (type == 'pictrueto') {
      imgList = that.data.pictrue_to;
    }
    var url = imgList[index];
    wx.showLoading({
      title: '删除中...'
    });
    if (url == '') {
      if (imgList.length == 1) {
        imgList = [];
      } else {
        imgList.splice(index, 1);
      }
      if (type && type == 'pictrueto') {
        that.setData({
          pictrue_to: imgList
        })
      }
      if (type && type == 'pictruefrom') {
        that.setData({
          pictrue_from: imgList
        })
      }
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000,
        success: function () {

        }
      });
      return false;
    }
    util.putData("/atapi/delivery/process/deleteFile", {
      url: url
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        if (imgList.length == 1) {
          imgList = [];
        } else {
          imgList = util.arrayDeleteWithIndex(imgList, index, 1);
        }
        if (type == 'pictrueto') {
          that.setData({
            pictrue_to: imgList
          })
        } else {
          that.setData({
            pictrue_from: imgList
          })
        }
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {

          }
        });
      }
    });
  },
  previewImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var current = e.currentTarget.dataset.url
    var pictruelist = that.data.pictrue_from;
    if (type == 'pictrueto') {
      pictruelist = that.data.pictrue_to;
    }
    wx.previewImage({
      current: current,
      urls: pictruelist
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})